package com.shqcjd.sinopecdemomobile.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.DefectManageBean;
import com.shqcjd.sinopecdemomobile.model.pojo.DefectManageTypeBean;
import com.shqcjd.sinopecdemomobile.ui.adapter.DefectManageAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.Config;
import com.shqcjd.sinopecdemomobile.util.WrapContentLinearLayoutManager;
import com.shqcjd.sinopecdemomobile.widget.DateDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

public class DefectManageActivity extends BaseActivity {
    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.rv_defect_manage)
    RecyclerView rvDefectManage;
    @BindView(R.id.sr_defect_manage)
    SwipeRefreshLayout srDefectManage;
    @BindView(R.id.et_defect_manage)
    EditText etDefectManage;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.sp_pop_defect_state)
    Spinner spPopDefectState;
    @BindView(R.id.sp_pop_defect_type)
    Spinner spPopDefectType;
    @BindView(R.id.tv_pop_defect_time)
    TextView tvPopDefectTime;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @BindView(R.id.ll_pop_content)
    LinearLayout ll_pop_content;
    @BindView(R.id.ll_defect_select)
    LinearLayout llDefectSelect;
    @BindView(R.id.btn_pop_commit)
    Button btnPopCommit;
    @BindView(R.id.btn_pop_reset)
    Button btnPopReset;

    private Context context;
    private DefectManageAdapter defectManageAdapter;
    private List<DefectManageBean.ListBean> mList = new ArrayList<>();
    private DateDialog dateDialog;
    List typeList = new ArrayList<String>();
    List<DefectManageTypeBean> tList = new ArrayList<>();

    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    private String strSearch = "";
    private int typeId = 0;//设备类型的id
    private int stateId = 0;//消缺状态 不传全部 false未消缺 true已消缺
    private String bTime = "";//开始时间
    private String eTime = "";//结束时间


    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_defect_manage;
    }

    @Override
    public void init() {
        super.init();
        strSearch = getIntent().getStringExtra("kks")==null?"":getIntent().getStringExtra("kks");
    }

    @Override
    public void initView() {
        super.initView();
        context = this;
        tvIncludeTitle.setText("维保缺陷");

        List stateList = new ArrayList<String>();
        stateList.add("全部");
        stateList.add("未消缺");
        stateList.add("已消缺");
        ArrayAdapter stateAdapter = new ArrayAdapter<String>(this, R.layout.item_spinner, stateList);
        stateAdapter.setDropDownViewResource(R.layout.item_spinner);
        spPopDefectState.setAdapter(stateAdapter);


        tvPopDefectTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dateDialog == null) {
                    dateDialog = new DateDialog(context);
                    dateDialog.setOnCheckDate(new DateDialog.setOnCheckDateListener() {
                        @Override
                        public void onCheckDate(String time, String endTime) {
                            bTime = time;
                            eTime = endTime;
                            tvPopDefectTime.setText(bTime+" - "+endTime);
                            refreshData();
                        }
                    });
                }
                dateDialog.show();
            }
        });

        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        srDefectManage.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

        etDefectManage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                strSearch = s.toString();
//                refreshData();
            }
        });

        spPopDefectState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                stateId = position;
//                refreshData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spPopDefectType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0){
                    typeId = 0;
                }else if(position>1){
                    typeId = tList.get(getListValue(typeList.get(position)+"")).value;
                }
//                refreshData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl.setVisibility(View.GONE);
            }
        });
        ll_pop_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        llDefectSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl.setVisibility(rl.getVisibility()==View.GONE?View.VISIBLE:View.GONE);
            }
        });

        btnPopCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshData();
                rl.setVisibility(View.GONE);
            }
        });

        btnPopReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                spPopDefectState.setSelection(0);
                spPopDefectType.setSelection(0);
                bTime = "";
                eTime = "";
                tvPopDefectTime.setText("开始时间 - 结束时间");
            }
        });

        refreshData();
        getTypeList();
    }

    private void refreshData() {
        refreshOrLoadMore();
        srDefectManage.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        mList.clear();
        getDataList(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getDataList(page + 1);
    }

    private void refreshOrLoadMore(){
        if(defectManageAdapter!=null){
            defectManageAdapter.notifyLoadMoreToLoading();
        }
    }


    private void getDataList(int p) {
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex",p+"");
        map.put("pageSize", Config.PAGE_TOTAL +"");
        map.put("kks", strSearch);
        map.put("equipmentTypeId",typeId+"");
        if(stateId!=0){
            map.put("state", (stateId==2?false:true)+"");
        }
        map.put("beginTime", bTime);
        map.put("endTime", eTime);
        ApiService.defectManageHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<DefectManageBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<DefectManageBean> responseData) {
                        if(responseData.retCode!=10000){
                            return;
                        }
                        mList.addAll(responseData.data.list);
                        if (defectManageAdapter == null) {
                            rvDefectManage.setLayoutManager(new WrapContentLinearLayoutManager(context));
                            defectManageAdapter = new DefectManageAdapter(mList,context);
                            rvDefectManage.setAdapter(defectManageAdapter);
                            defectManageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    Intent it = new Intent(context, DefectInfoActivity.class);
                                    it.putExtra("dId", mList.get(position).exceptionId);
                                    startActivity(it);
                                }
                            });
                            defectManageAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                @Override
                                public void onLoadMoreRequested() {
                                    rvDefectManage.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            int pageSize = responseData.data.total%Config.PAGE_TOTAL==0?responseData.data.total/Config.PAGE_TOTAL:responseData.data.total/Config.PAGE_TOTAL+1;
                                            if (page >= pageSize) {
                                                rvDefectManage.post(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        defectManageAdapter.loadMoreEnd();
                                                    }
                                                });
                                            } else {
                                                loadMoreData();
                                            }
                                        }
                                    });
                                }
                            });
                        }
                        if (isRefreshOrLoadMore == 1) {
                            page = page + 1;
                            defectManageAdapter.loadMoreComplete();
                        }
                        if(mList.size()==0){
                            rlIsnull.setVisibility(View.VISIBLE);
                        }else{
                            rlIsnull.setVisibility(View.INVISIBLE);
                        }
                        defectManageAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srDefectManage.setRefreshing(false);
                    }
                });
    }

    private void getTypeList() {
        ApiService.defectManageTypeHttp()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<DefectManageTypeBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<DefectManageTypeBean>> responseData) {
                        tList = responseData.data;
                        typeList.add("全部");
                        for(int i=0; i<responseData.data.size(); i++){
                             typeList.add(responseData.data.get(i).label);
                        }
                        ArrayAdapter arr_adapter = new ArrayAdapter<String>(context, R.layout.item_spinner, typeList);
                        arr_adapter.setDropDownViewResource(R.layout.item_spinner);
                        spPopDefectType.setAdapter(arr_adapter);
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private int getListValue(String str){
       for(int i=0; i<tList.size(); i++){
           if(str.equals(tList.get(i).label)){
               return i;
           }
       }
       return 0;
    }
}
